package leihua.crm.workbench.web.controller;

import leihua.crm.commons.contants.Contants;
import leihua.crm.commons.domain.ReturnObject;
import leihua.crm.commons.utils.DateUtils;
import leihua.crm.commons.utils.UUIDUtils;
import leihua.crm.settings.domain.DicValue;
import leihua.crm.settings.domain.User;
import leihua.crm.settings.mapper.DicValueMapper;
import leihua.crm.settings.mapper.UserMapper;
import leihua.crm.settings.service.DicValueService;
import leihua.crm.settings.service.UserService;
import leihua.crm.workbench.domain.*;
import leihua.crm.workbench.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author leiHua
 * @Date 2022/10/24 22:27
 */
@Controller
public class TranController {
    @Autowired
    DicValueService dicValueService;
    @Autowired
    UserService userService;
    @Autowired
    ActivityService activityService;
    @Autowired
    ContactsService contactsService;
    @Autowired
    CustomerService customerService;
    @Autowired
    TranService tranService;
    @Autowired
    TranRemarkService tranRemarkService;
    @Autowired
    TranHistoryService tranHistoryService;


    @RequestMapping("/workbench/transaction/index.do")
    public String index(HttpServletRequest request) {
        List<DicValue> stage = dicValueService.queryDicValueByTypeCode("stage");
        List<DicValue> source = dicValueService.queryDicValueByTypeCode("source");
        List<DicValue> transactionType = dicValueService.queryDicValueByTypeCode("transactionType");
        request.setAttribute("stageList", stage);
        request.setAttribute("sourceList", source);
        request.setAttribute("transactionTypeList", transactionType);

        return "workbench/transaction/index";
    }

    @RequestMapping("/workbench/transaction/toSave.do")
    public String save(HttpSession session, HttpServletRequest request) {
        List<DicValue> stage = dicValueService.queryDicValueByTypeCode("stage");
        List<DicValue> source = dicValueService.queryDicValueByTypeCode("source");
        List<DicValue> transactionType = dicValueService.queryDicValueByTypeCode("transactionType");
        List<User> userList = userService.queryAllUsers();
        request.setAttribute("stageList", stage);
        request.setAttribute("sourceList", source);
        request.setAttribute("transactionTypeList", transactionType);
        request.setAttribute("userList", userList);
        return "workbench/transaction/save";
    }

    //市场活动源 查询数据
    @RequestMapping("/workbench/transaction/queryActivity.do")
    @ResponseBody
    public Object queryActivity(String activityName) {
        List<Activity> activityList = activityService.queryActivityByActivityName(activityName);
        return activityList;
    }
    //联系人 查询的数据
    @RequestMapping("/workbench/transaction/queryContacts.do")
    @ResponseBody
    public Object queryContacts(String contactsName) {
        List<Contacts> contactList = contactsService.queryContactsByContactsName(contactsName);
        return contactList;
    }
    //根据阶段名 获取可能性
    @RequestMapping("/workbench/transaction/getPossibilityByStage.do")
    @ResponseBody
    public Object getPossibilityByStage(String stageName) {
        ResourceBundle bundle = ResourceBundle.getBundle("possibility");
        String possibility = bundle.getString(stageName);
        return possibility;
    }
    //客户自动补全的 数据
    @RequestMapping("/workbench/transaction/queryCustomerName.do")
    @ResponseBody
    public Object queryCustomerName(String customerName) {
        List<String> nameList = customerService.queryCustomerNameByCustomerName(customerName);
        return nameList;
    }

    @RequestMapping("/workbench/transaction/saveCreateTran.do")
    @ResponseBody
    public Object saveCreateTran(@RequestParam Map<String, Object> map, HttpSession session) {
        ReturnObject returnObject = new ReturnObject();
        map.put(Contants.SESSION_USER, session.getAttribute(Contants.SESSION_USER));
        try {
            tranService.saveCreateTran(map);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加失败");
        }
        return returnObject;
    }

    //点击交易的信息连接  展示的详情页  ，交易信息、交易备注、交易历史
    @RequestMapping("/workbench/transaction/detailTran.do")
    public String detailTran(String id, HttpServletRequest request) {
        Tran tran = null;
        List<TranRemark> remarkList = null;
        List<TranHistory> historyList = null;
        List<DicValue> stageList = null;
        try {
            tran = tranService.queryTranForDetailByTranId(id);
            remarkList = tranRemarkService.queryTranRemarkForDetailByTranId(id);
            historyList = tranHistoryService.queryTranHistoryForDetailByTranId(id);
            ResourceBundle bundle = ResourceBundle.getBundle("possibility");
            String possibility = bundle.getString(tran.getStage());
            tran.setPossibility(possibility);
            stageList = dicValueService.queryDicValueByTypeCode("stage");
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("stageList", stageList);
        request.setAttribute("tran", tran);
        request.setAttribute("remarkList", remarkList);
        request.setAttribute("historyList", historyList);
        return "workbench/transaction/detail";
    }

    @RequestMapping("/workbench/transaction/queryTranForPageByCondition.do")
    @ResponseBody
    public Object queryTranForPageByCondition(int pageNo, int pageSize, String owner,
                                              String name, String customerId, String contactsId,
                                              String stage, String type, String source
    ) {
        int beginNo = (pageNo - 1) * pageSize;
        HashMap<String, Object> map = new HashMap<>();
        map.put("contactsId", contactsId);  //联系人名字
        map.put("owner", owner);
        map.put("source", source);
        map.put("customerId", customerId);  //客户名字
        map.put("name", name);
        map.put("stage", stage);
        map.put("type", type);
        map.put("pageSize", pageSize);
        map.put("beginNo", beginNo);
        HashMap<String, Object> data = new HashMap<>();
        try {
            List<Tran> tranList = tranService.queryTranForPageByCondition(map);
            int totalRows = tranService.queryCountOfTranByCondition(map);
            data.put("tranList", tranList);
            data.put("totalRows", totalRows);
            data.put("code", "1");
        } catch (Exception e) {
            e.printStackTrace();
            data.put("code", '0');
        }
        return data;
    }

    //跳转到修改信息的页面 ，
    @RequestMapping("/workbench/transaction/toEditTran.do")
    public String toEditTran(String tranId, HttpServletRequest request) {
        // 该条信息的详情
        Tran tran = tranService.queryTranForDetailByTranId(tranId);
        List<User> userList = userService.queryAllUsers();
        List<DicValue> sourceList = dicValueService.queryDicValueByTypeCode("source");
        List<DicValue> typeList = dicValueService.queryDicValueByTypeCode("transactionType");
        List<DicValue> stageList = dicValueService.queryDicValueByTypeCode("stage");
        request.setAttribute("userList", userList);
        request.setAttribute("tran", tran);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("typeList", typeList);
        request.setAttribute("stageList", stageList);

        //获取交易信息的外键id
        Tran tranForDicValue = tranService.queryTranById(tranId);
        String stageId = tranForDicValue.getStage();
        String typeId = tranForDicValue.getType();
        String contactsId = tranForDicValue.getContactsId();
        String customerId = tranForDicValue.getCustomerId();
        String activityId = tranForDicValue.getActivityId();
        String ownerId = tranForDicValue.getOwner();
        String sourceId = tranForDicValue.getSource();
        request.setAttribute("stageId",stageId);
        request.setAttribute("typeId",typeId);
        request.setAttribute("contactsId",contactsId);
        request.setAttribute("customerId",customerId);
        request.setAttribute("activityId",activityId);
        request.setAttribute("ownerId",ownerId);
        request.setAttribute("sourceId",sourceId);
        return "workbench/transaction/edit";
    }

    @RequestMapping("/workbench/transaction/editTran.do")
    @ResponseBody
    public Object editTran(Tran tran,HttpSession session){
        ReturnObject returnObject = new ReturnObject();
        try {
            String customerName = tran.getCustomerId();
            Customer customer = customerService.queryCustomerByName(customerName);
            tran.setCustomerId(customer.getId());
            User user = (User) session.getAttribute(Contants.SESSION_USER);
            tran.setEditBy(user.getId());
            tran.setEditTime(DateUtils.formateDateTime(new Date()));
            int i=tranService.editTranSelective(tran);
            if (i==0){
                returnObject.setCode("0");
                returnObject.setMessage("修改失败，请联系管理员");
            }else{
                returnObject.setCode("1");
            }

        } catch (Exception e) {
            returnObject.setCode("0");
            returnObject.setMessage("修改失败，请联系管理员");
            e.printStackTrace();
        }
        return returnObject ;
    }
    @RequestMapping("/workbench/transaction/deleteByIds.do")
    @ResponseBody
    public Object deleteByIds(String[]id){
        ReturnObject returnObject = new ReturnObject();
        try {
            int i = tranService.deleteTranByIds(id);
            if (i>0){
                returnObject.setCode("1");
            }else{
                returnObject.setCode("0");
            }
        } catch (Exception e) {
            returnObject.setCode("0");
            returnObject.setMessage("删除失败，请联系管理员");
            e.printStackTrace();
        }
        return returnObject;
    }

    //添加一条交易备注请求：
    @RequestMapping("/workbench/transaction/insertTranRemark.do")
    @ResponseBody
    public Object insertTranRemark(TranRemark tranRemark,HttpSession session){
        ReturnObject returnObject = new ReturnObject();
        tranRemark.setId(UUIDUtils.getUUID());
        User user=(User) session.getAttribute(Contants.SESSION_USER);
        tranRemark.setCreateBy(user.getId());
        tranRemark.setCreateTime(DateUtils.formateDateTime(new Date()));
        tranRemark.setEditFlag(Contants.REMARK_DEIT_FLAG_NO_EDITED);
        try {
            int i = tranRemarkService.saveTranRemark(tranRemark);
            if (i>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(tranRemark);
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("保存失败，请联系管理员");
            }
        } catch (Exception e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("保存失败，请联系管理员");
            e.printStackTrace();
        }
        return returnObject;
    }



}
